package com.example.demo.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.example.demo.service.AliService;
import org.springframework.stereotype.Service;

@Service
public class AliServiceImpl implements AliService {
    private final static String accessKeyId = "LTAI5tPDxtsWCBAN78hewfdm";
    private final static String accessKeySecret = "gNePZNAOZ1J98uNpg2JWL3yTYqynLL";

    public static Client getClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static String smsCode(){
        String random=(int)((Math.random()*9+1)*100000)+"";
        System.out.println("创建的验证码为："+random);
        return random;
    }

    @Override
    public String sendCode(String phone) throws Exception {
        String smsCode = AliServiceImpl.smsCode();
        Client client = AliServiceImpl.getClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(phone)
                .setTemplateParam(String.format("{\"code\":\"%s\"}", smsCode));
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse response = client.sendSms(sendSmsRequest);
        System.out.println(response.body.message);
        if(response.body.message.equals("OK")){
            return smsCode;
        }
        return null;
    }

    public static void main(String[] args) throws Exception {
        AliServiceImpl service = new AliServiceImpl();
        String code = service.sendCode("17347950899");
        System.out.println(code);
    }
}
